<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="问卷模板" prop="templateId">
        <el-select
          :disabled="formType === 'update'"
          v-model="formData.templateId"
          clearable
          placeholder="请选择问卷模板"
        >
          <el-option
            v-for="item in templates"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formType === 'create'" label="类型" prop="userId">
        <el-radio-group v-model="formData.type">
          <el-radio :label="false">就诊人</el-radio>
          <el-radio :label="true">标签</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formType === 'update' || formData.type === false" label="就诊人" prop="userId">
        <el-cascader
          v-model="formData.userIds"
          :options="userPatients"
          :props="{ label: 'name', value: 'id' }"
          style="width: 100%"/>
      </el-form-item>
      <el-form-item v-if="formData.type === true" label="标签" prop="locationIds">
        <el-cascader
          v-model="formData.tags"
          :options="tagsTree"
          :props="{ multiple: true }"
          clearable
          style="width: 100%"
          @change="getTagsPeopleCount"
        />
      </el-form-item>
      <el-form-item v-if="formData.type === true" label="" prop="locationIds">
        <p>当前标签下就诊人数量：{{peopleCount}}</p>
      </el-form-item>
      <el-form-item label="问卷标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入问卷标题" />
      </el-form-item>
      <el-form-item label="随访简介" prop="briefDescribe">
        <el-input v-model="formData.briefDescribe" placeholder="请输入随访简介" />
      </el-form-item>
      <el-form-item label="开始时间" prop="beginTime">
        <el-date-picker
          v-model="formData.beginTime"
          type="datetime"
          value-format="x"
          placeholder="选择问卷开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          value-format="x"
          placeholder="选择问卷结束时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { QuestionnaireRecordApi, QuestionnaireRecord } from '@/api/business/questionnairerecord'
import {BizUserApi} from "@/api/business/user";
import {QuestionnaireTemplateApi} from "@/api/business/questionnairetemplate";
import {TagApi} from "@/api/business/tag";
import {FollowUpRecord} from "@/api/business/followuprecord";
import {UserPatientApi} from "@/api/business/userpatient";

/** 问卷发起记录 表单 */
defineOptions({ name: 'QuestionnaireRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  templateId: undefined,
  userId: undefined,
  userIds: [],
  type: false,
  adminUserId: undefined,
  title: undefined,
  briefDescribe: undefined,
  beginTime: undefined,
  endTime: undefined,
  durationHour: undefined,
  tags: [],
})
const formRules = reactive({
  templateId: [{ required: true, message: '问卷模板不能为空', trigger: 'blur' }],
  userIds: [{ required: true, message: '就诊人不能为空', trigger: 'blur' }],
  adminUserId: [{ required: true, message: '医生ID不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '问卷标题不能为空', trigger: 'blur' }],
  briefDescribe: [{ required: true, message: '问卷简介不能为空', trigger: 'blur' }],
  beginTime: [{ required: true, message: '问卷开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '问卷结束时间不能为空', trigger: 'blur' }],
  durationHour: [{ required: true, message: '时长（小时）不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

let userPatients = ref()
/** 查询用户与就诊人树 */
const getUserPatientTree = async () => {
  userPatients.value = await BizUserApi.getBizUserTree()
}

let templates = ref()
/** 获取模板 */
const getTemplates = async () => {
  templates.value = await QuestionnaireTemplateApi.getQuestionnaireTemplateAll()
}

const tagsTree = ref() // 树形结构

/** 获得已开通城市树 */
const getTagsTree = async () => {
  tagsTree.value = await TagApi.getTagTree()
}


let peopleCount = ref()
const getTagsPeopleCount = async () => {
  const data = formData.value as unknown as FollowUpRecord
  peopleCount.value = await UserPatientApi.getTagsPeopleCount(data)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  peopleCount.value = 0
  await getUserPatientTree()
  await getTemplates()
  await getTagsTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await QuestionnaireRecordApi.getQuestionnaireRecord(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as QuestionnaireRecord
    if (formType.value === 'create') {
      await QuestionnaireRecordApi.createQuestionnaireRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuestionnaireRecordApi.updateQuestionnaireRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    templateId: undefined,
    userId: undefined,
    userIds: [],
    type: false,
    adminUserId: undefined,
    title: undefined,
    briefDescribe: undefined,
    beginTime: undefined,
    endTime: undefined,
    durationHour: undefined,
    tags: [],
  }
  formRef.value?.resetFields()
}
</script>
